import { Injectable } from "@nestjs/common";
import { PassportStrategy } from "@nestjs/passport";
import { ExtractJwt, Strategy } from "passport-jwt";
import { jwtConstants } from "./constants";

export interface JwtPayload {
  sub: number;
  username: string,
  role: string;
}

@Injectable()
// 验证请求头中的token
export class JwtAuthStrategy extends PassportStrategy(Strategy, "jwt") {
  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false, // 自动处理 token 过期
      secretOrKey: jwtConstants.secret,
    });
  }
  async validate(payload: JwtPayload) {
    // payload 验证通过，返回用户信息
    return {
      username: payload.username,
      id: payload.sub,
      role: payload.role, // 包含角色
    };
  }
}
